<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.platforms" multiple placeholder="请选择发布平台" clearable>
          <el-option v-for="item in platformList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input placeholder="请选择绑定的店铺" disabled v-model="searchCondition.store_name" clearable>
          <template #append>
            <el-button :icon="Search" @click="handleSelectStore" v-show="!searchCondition.store_name">查询</el-button>
            <el-button :icon="CircleClose" @click="handleClearStoreInfo" v-show="searchCondition.store_name">删除</el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.cat_id1" placeholder="请选择商品分类" clearable @change="handleChangeCategory">
          <el-option v-for="item in category1List" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.order_rent_type_id" placeholder="请选择租赁模式" clearable>
          <el-option v-for="item in optionalOrderRentTypeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.is_on_sale" placeholder="请选择商品状态" clearable>
          <el-option v-for="item in saleList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.goods_name" placeholder="手机型号" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-space wrap class="mb20">
      <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="changeFormStatus('add')" v-permission="'add'">新增</el-button>
      <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete">
        <template #reference>
          <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除</el-button>
        </template>
      </el-popconfirm>
      <el-button type="success" :icon="EditPen" plain :disabled="disabledbtn" v-permission="'updateSale'" @click="handleBatchUpdatetatus('1')">批量上架</el-button>
      <el-button type="danger" :icon="EditPen" plain :disabled="disabledbtn" v-permission="'updateSale'" @click="handleBatchUpdatetatus('0')">批量下架</el-button>
      <el-button type="warning" :icon="EditPen" plain :disabled="disabledbtn" v-permission="'updateSale'" @click="handleBatchUpdatetatus('2')">批量缺货</el-button>
    </el-space>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="id" width="76" align="center"> </el-table-column>
      <el-table-column prop="original_img" label="图片" width="150" align="center">
        <template #default="scope">
          <el-image style="width: 60px; height: 60px" :src="IMG_URL + scope.row.original_img"> </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="cat_id1" label="商品分类" width="100" align="center">
        <template #default="scope">
          <div>{{ categoryObj[scope.row.cat_id1] }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="platform" label="发布平台" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag v-for="item in scope.row.platform" :key="item.id">{{ item.platform_name }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="order_rent_types" label="租赁模式" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag v-for="item in scope.row.order_rent_types" :key="item.id" type="success">{{ item.name }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="goods_name" label="手机型号" align="center" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="store" label="绑定店铺" align="center">
        <template #default="scope">
          <div class="ibDraggable" v-if="scope.row.store">
            <div>名称：{{ scope.row.store.store_name }}</div>
            <div>手机号：{{ scope.row.store.store_phone }}</div>
            <div v-if="scope.row.publishUser && scope.row.is_guest_publish">C端发布者：{{ scope.row.publishUser.mobile }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="is_on_sale" label="状态" width="100" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag :type="scope.row.is_on_sale == 1 ? 'success' : scope.row.is_on_sale == 2 ? 'warning' : scope.row.is_on_sale == 0 ? 'danger' : 'primary'">{{ scope.row.statusName }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="aliGoods.spu_status_name" label="支付宝商品状态" align="center">
        <template #default="scope">
          <div class="" v-if="scope.row.aliGoods">
            <el-tooltip class="item" effect="dark" :content="scope.row.aliGoods.audit_msg" placement="top" v-if="scope.row.aliGoods.audit_msg">
              <div>{{ scope.row.aliGoods.spu_status_name }}</div>
            </el-tooltip>
            <div v-else>{{ scope.row.aliGoods.spu_status_name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view')">查看</el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'edit'" @click="handleViewEdit(scope.row, 'edit')">编辑</el-button>
            <div v-permission="'delete'">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo([scope.row.id])">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <el-button type="success" link :icon="EditPen" :disabled="scope.row.is_on_sale == '1'" v-permission="'updateSale'" @click="handleUpdatetatus(scope.row, '1')">上架 </el-button>
            <el-button type="danger" link :icon="EditPen" :disabled="scope.row.is_on_sale == '0'" v-permission="'updateSale'" @click="handleUpdatetatus(scope.row, '0')">下架 </el-button>
            <el-button type="warning" link :icon="EditPen" :disabled="scope.row.is_on_sale == '2'" v-permission="'updateSale'" @click="handleUpdatetatus(scope.row, '2')">缺货 </el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'syncAliGoods'" v-show="scope.row.platformList.includes('alipayPlatform')" @click="handleSyncAliGoodsInfo(scope.row)">同步支付宝商品库</el-button>
            <el-button
              type="primary"
              link
              :icon="EditPen"
              v-permission="'syncAliGoodsStatus'"
              v-show="scope.row.aliGoods && scope.row.aliGoods.spu_status === 'DELISTING' && scope.row.platformList.includes('alipayPlatform')"
              @click="handleSyncAliGoodsStatusInfo(scope.row, 1, '出售中')"
              >上架支付宝库商品</el-button
            >
            <el-button
              type="primary"
              link
              :icon="EditPen"
              v-permission="'syncAliGoodsStatus'"
              v-show="scope.row.aliGoods && scope.row.aliGoods.spu_status === 'AVAILABLE' && scope.row.platformList.includes('alipayPlatform')"
              @click="handleSyncAliGoodsStatusInfo(scope.row, 0, '已下架')"
              >下架支付宝库商品</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <!-- 选择店铺 -->
    <SelectStoreDialog v-model:edit-visible="storeVisible" @handleSuccess="handleSelectedData" />
  </div>
</template>

<script setup lang="ts">
import SelectStoreDialog from "@/components/user/storeManager/storeInfo/SelectStoreDialog.vue";
import { View, Delete, EditPen, Search, Refresh, Plus, CircleClose } from "@element-plus/icons-vue";
import { IMG_URL } from "@/utils/config";
import type { IKeyedMap, ViewMode, ViewModeFilter } from "@/types/common";
import type { IDictData } from "@/types/dict";
import { useState } from "@/hooks/useState.ts";
import type { IChangeGoodsStatus, IGoodsList, IRentMobileOrderType, ISearchGoods } from "@/types/rentMachineManage/phoneInfo";
import type { IStoreInfoList } from "@/types/storeManager/store";
import { deleteGoodsInfo, getGoodsList, putSyncAliGoodsInfo, putSyncAliGoodsStatusInfo, putUpdateIsOnSaleInfo } from "@/utils/api/admin/goods/goods";
import type { IGoodsCategory } from "@/types/rentMachineManage/goodsCategory";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  category1List: Array<IGoodsCategory>;
  platformList: Array<IDictData>;
  orderRentTypeList: Array<IRentMobileOrderType>;
  saleList: Array<IDictData>;
  categoryObj: IKeyedMap<string>;
}
const { category1List, platformList, orderRentTypeList, saleList, categoryObj } = defineProps<Props>();

const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleViewEdit: [id: number, code: ViewModeFilter];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
/* 显示隐藏选择店铺 */
const storeVisible = ref<boolean>(false);
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */

const total = ref(0);
const searchCondition = reactive<ISearchGoods>({
  cat_id1: "",
  is_on_sale: "",
  publisher: "",
  store_id: "",
  store_name: "",
  mobile: "",
  order_rent_type_id: "",
  platforms: [],
  goods_name: "",
  size: 10,
  current: 1
});
const tableList = ref<Array<IGoodsList>>([]);

const optionalOrderRentTypeList = computed(() => {
  if ([639].includes(searchCondition.cat_id1 as number)) {
    /* 共享手机 */
    return orderRentTypeList.filter(item => [24, 25, 26, 27, 30].includes(item.is_advance));
  } else if ([9].includes(searchCondition.cat_id1 as number)) {
    /* 精品手机 */
    return orderRentTypeList.filter(item => [21].includes(item.is_advance));
  }
  /* 租赁手机 */
  return orderRentTypeList.filter(item => [13, 14, 40, 43, 44, 45, 47, 48, 49].includes(item.is_advance));
});

onMounted(() => {
  getTableInfo();
});
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.cat_id1 = "";
  searchCondition.is_on_sale = "";
  searchCondition.store_id = "";
  searchCondition.store_name = "";
  searchCondition.mobile = "";
  searchCondition.order_rent_type_id = "";
  searchCondition.platforms = [];
  searchCondition.goods_name = "";

  searchCondition.current = 1;
  searchCondition.size = 10;

  getTableInfo();
}

/**
 * 切换表单状态（ 添加、编辑、查看 ，隐藏none ）
 */
function changeFormStatus(state: ViewMode) {
  // formStatus.value = state;
  emit("handleAdd", state);
}

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getGoodsList<IGoodsList, ISearchGoods>(searchCondition)
    .then(res => {
      res.result.data.forEach(item => {
        if (item.is_on_sale === 1) {
          item.statusName = "上架";
        } else if (item.is_on_sale === 0) {
          item.statusName = "下架";
        } else if (item.is_on_sale === 2) {
          item.statusName = "缺货";
        } else {
          item.statusName = "-";
        }
        item.platformList = item.platform.map(_item => _item.platform);
      });
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IGoodsList, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: IGoodsList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 批量删除 */
function batchDelete() {
  /* 获取选中的数据 */
  let selection = multipleTableRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let idArray = [];
  for (const item of selection) {
    idArray.push(item.id);
  }
  deleteInfo(idArray);
}
/* 删除后的信息 */
function deleteInfo(idArray: Array<number>) {
  toggleState(true);
  deleteGoodsInfo({ idArray })
    .then(() => {
      /* 当删除成功后，删除对应选中的数据或单个数据 */
      tableList.value = tableList.value.filter((item: IGoodsList) => !idArray.includes(item.id));
      ElMessage.success(`成功删除了${idArray.length}条数据`);
      multipleTableRef.value!.clearSelection();
      total.value = total.value - idArray.length;
    })
    .catch((error: Error) => {
      console.log(error);
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 批量处理 上下架，缺货*/
function handleBatchUpdatetatus(status: string) {
  let selection = multipleTableRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let ids = [];
  for (const item of selection) {
    ids.push(item.id);
  }
  updateStatus({ ids, is_on_sale: status });
}

/* 上下架，缺货 */
function handleUpdatetatus(row: IGoodsList, status: string) {
  updateStatus({ ids: [row.id], is_on_sale: status });
}

/* 更新商品状态 */
function updateStatus(data: IChangeGoodsStatus) {
  toggleState(true);
  putUpdateIsOnSaleInfo(data)
    .then(() => {
      data.ids.forEach(id => {
        tableList.value
          .filter(item => item.id === id)
          .forEach(item => {
            item.is_on_sale = data.is_on_sale;
            item.statusName = saleList.find(s => s.dictValue == data.is_on_sale)?.dictLabel || "";
            console.log(item);
          });
      });
      ElMessage.success(`数据修改成功`);
      /* 取消选择 */
      multipleTableRef.value!.clearSelection();
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 同步商品到支付宝库*/
function handleSyncAliGoodsInfo(row: IGoodsList) {
  toggleState(true);
  putSyncAliGoodsInfo({ id: row.id })
    .then(() => {
      ElMessage.success(`同步成功`);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 同步商品到支付宝库*/
function handleSyncAliGoodsStatusInfo(row: IGoodsList, type: number, typeName: string) {
  toggleState(true);
  putSyncAliGoodsStatusInfo({ id: row.id, type })
    .then(() => {
      ElMessage.success(`同步成功`);
      const item = tableList.value.find(item => item.id === row.id);
      if (item) {
        /* spu_status这个的类型可能有问题，后期对接支付宝的话再做 */
        item.aliGoods.spu_status = type + "";
        item.aliGoods.spu_status_name = typeName;
      }
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 选择店铺 */
function handleSelectStore() {
  storeVisible.value = true;
}
/* 清除店铺选择数据 */
function handleClearStoreInfo() {
  if (searchCondition.store_id == "") return;
  searchCondition.store_id = "";
  searchCondition.store_name = "";
  getTableInfo();
}
/* 选择选中的店铺数据 */
function handleSelectedData(list: IStoreInfoList[]) {
  searchCondition.store_id = list[0].id;
  searchCondition.store_name = list[0].store_name;
  getTableInfo();
}
/* 处理分类改变事件 */
function handleChangeCategory() {
  searchCondition.order_rent_type_id = "";
  searchCondition.publisher = "";
  searchCondition.store_id = "";
  searchCondition.store_name = "";
  searchCondition.mobile = "";
}
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}
</style>
